<template>
  <view class="jinuns">
    <BaNner :banner_img="ban_img"/>
    <!-- 栏目 -->
    <view class="column">
      <u-tabs name="name" :list="good_sort" :is-scroll="true" :current="current" @change="changeCategory"
        :bg-color="'background: #F2F2F2;'" :inactive-color="'#10100E;'" :active-color="'#23AC38'"
        :border-radius="'18'" :show-bar="true">
      </u-tabs>
    </view>
    
    <!-- 置顶视频 -->
    <view class="zd_viode" v-if="voldlist.length > 0">
      <video :id="'video_' + 0" 
             :src="'https://img.ukh5.com' + voldlist[0].file" 
             @error="videoErrorCallback"
             :danmu-list="danmuList" 
             controls 
             :poster="'https://img.ukh5.com' + voldlist[0].image"
             @play="handlePlay(0)" 
			 class="vid1"
             @pause="handlePause(0)">
      </video>
      <view class="v_title">
        <view class="name">{{voldlist[0].title}}</view>
        <view class="icon">
          <image src="/static/home/yj.png" mode="widthFix"></image>
          <view>{{voldlist[0].pv}}</view>
        </view>
      </view>
      <view class="tps">{{voldlist[0].describe}}</view>
    </view>
    
    <!-- 视频列表 -->
    <view class="v_list">
      <!-- 骨架屏 - 首次加载 -->
      <view class="skeleton-list" v-if="isFirstLoad && isLoading">
        <view class="skeleton-item" v-for="i in 6" :key="i">
          <view class="skeleton-img"></view>
          <view class="skeleton-title"></view>
          <view class="skeleton-desc"></view>
        </view>
      </view>
      
      <!-- 视频列表 -->
      <view class="list_itme" v-for="(item, index) in voldlist" :key="item.id || index" v-if="index > 0"
            :class="{ 'fade-in': !isFirstLoad }">
        <view class="viose">
			<video :id="'video_' + index"
			       :src="'https://img.ukh5.com' + item.file" 
			       @error="videoErrorCallback"
			       :danmu-list="danmuList" 
			       controls 
			       :poster="'https://img.ukh5.com' + item.image"
			       @play="handlePlay(index)" 
			       @pause="handlePause(index)">
			</video>
		</view>
        <view class="v_title">
          <view class="name">{{item.title}}</view>
          <view class="icon">
            <image src="/static/home/yj.png" mode="widthFix"></image>
            <view>{{item.pv}}</view>
          </view>
        </view>
        <view class="tps">{{item.describe}}</view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="isLoading && !isFirstLoad">
        <view class="loading-icon">
          <view class="dot"></view>
          <view class="dot"></view>
          <view class="dot"></view>
        </view>
        <text>正在加载更多视频...</text>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more-data" v-if="!isLoading && !hasMore && voldlist.length > 1">
        <text>已经到底了</text>
      </view>
      
      <!-- 空数据提示 -->
      <view class="empty-data" v-if="!isLoading && voldlist.length === 0">
        <image src="/static/empty.png" mode="aspectFit" v-if="false"/> <!-- 保留但隐藏图片 -->
        <text>暂无视频数据</text>
      </view>
    </view>
  </view>
</template>

<script>
import { jinlun_category, jinlun_list, product_banner } from '@/core/api/index.js'
export default {
  data() {
    return {
      good_sort: [],
      current: 0,
      voldlist: [],
      playingIndex: -1,
      isLoading: false,
      isFirstLoad: true,
      ban_img: '',
      page: 1, // 页码从1开始
      pageSize: 10,
      hasMore: true,
      danmuList: []
    }
  },
  onLoad() {
    this.loadCategoryList()
    this.loadBanner()
  },
  onReachBottom() {
    // 页面滚动到底部时触发加载更多
    if (!this.isLoading && this.hasMore) {
      this.loadMoreVideos()
    }
  },
  methods: {
    // 加载banner图片
    async loadBanner() {
      try {
        const data = await product_banner()
        data._data.list.forEach(res => {
          if (res.name == '金伦问答') {
            this.ban_img = res.image
          }
        })
      } catch (error) {
        console.error('获取banner失败:', error)
      }
    },
    
    // 切换分类
    async changeCategory(index) {
      console.log('切换栏目:', index)
      this.current = index
      this.resetList()
      await this.loadVideosByCategory(this.good_sort[index].id)
    },
    
    // 加载分类列表
    async loadCategoryList() {
      try {
        this.isLoading = true
        const data = await jinlun_category()
        this.good_sort = data._data.list
        console.log('分类列表:', this.good_sort)
        
        if (this.good_sort.length > 0) {
          console.log('加载第一个分类的视频')
          await this.loadVideosByCategory(this.good_sort[0].id)
        }
      } catch (error) {
        console.error('获取栏目失败:', error)
      } finally {
        this.isLoading = false
      }
    },
    
    // 加载视频列表
    async loadVideosByCategory(categoryId, isLoadMore = false) {
      // if (this.isLoading) return
      
      this.isLoading = true
      
      try {
        // 页码从1开始
        let params = {
          categoryId: categoryId,
          page: isLoadMore ? this.page + 1 : 1, // 首次加载和加载更多都从1开始
          pageSize: this.pageSize
        }
        
        console.log('请求参数:', params)
        
        const data = await jinlun_list(params)
        const newList = data._data.list || []
        
        console.log('获取的视频数据:', newList)
        
        // 处理数据
        if (isLoadMore) {
          // 加载更多，追加数据
          this.voldlist = [...this.voldlist, ...newList]
          this.page++ // 页码递增
        } else {
          // 刷新数据
          this.voldlist = newList
          this.page = 1 // 重置页码为1
        }
        
        // 判断是否还有更多数据
        this.hasMore = newList.length >= this.pageSize
        
        // 首次加载完成
        if (this.isFirstLoad) {
          this.isFirstLoad = false
        }
        
      } catch (error) {
        console.error('获取视频列表失败:', error)
      } finally {
        this.isLoading = false
      }
    },
    
    // 加载更多视频
    async loadMoreVideos() {
      console.log('加载更多视频...')
      await this.loadVideosByCategory(this.good_sort[this.current].id, true)
    },
    
    // 重置列表状态
    resetList() {
      this.voldlist = []
      this.page = 1 // 重置页码为1
      this.hasMore = true
      this.playingIndex = -1
      this.isFirstLoad = true
    },
    
    // 处理视频播放
    handlePlay(index) {
      console.log(`播放视频 ${index}，当前播放索引: ${this.playingIndex}`)
      
      // 先暂停其他视频
      if (this.playingIndex !== -1 && this.playingIndex !== index) {
        this.pauseVideo(this.playingIndex)
      }
      
      // 设置当前播放索引
      this.playingIndex = index
      
      // 延迟播放，确保DOM已更新
      this.$nextTick(() => {
        setTimeout(() => {
          const videoContext = uni.createVideoContext(`video_${index}`)
          videoContext.play()
        }, 100)
      })
    },
    
    // 处理视频暂停
    handlePause(index) {
      console.log(`暂停视频 ${index}，当前播放索引: ${this.playingIndex}`)
      if (this.playingIndex === index) {
        this.playingIndex = -1
      }
    },
    
    // 暂停指定视频
    pauseVideo(index) {
      console.log(`尝试暂停视频 ${index}`)
      const videoContext = uni.createVideoContext(`video_${index}`)
      videoContext.pause()
    },
    
    // 视频加载错误处理
    videoErrorCallback(e) {
      console.log('视频加载错误:', e)
      uni.showToast({
        title: '视频加载失败',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.jinuns {
  .login {
    width: 100%;
    image {
      width: 100%;
      height: auto;
    }
  }
}

.column {
  width: 100%;
}

.zd_viode,
.v_list {
  width: 100%;
  padding: 32rpx 30rpx 26rpx;
  .vid1 {
    width: 100%;
    height: 378rpx;
	border-radius: 20rpx;
  }

  .v_title {
    display: flex;
    margin-top: 15rpx;
    width: 100%;
    justify-content: space-between;
    .name {
      font-weight: 700;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-top: 5rpx;
      width: 600rpx;
      font-size: 34rpx;
      color: #000000;
    }

    .icon {
      display: flex;
      color: #666666;
      font-size: 24rpx;
      align-items: center;
      image {
        width: 28rpx;
        margin-right: 10rpx;
        height: auto;
      }
    }
  }

  .tps {
    font-size: 28rpx;
    color: #666666;
    margin-top: 10rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-top: 5rpx;
    width: 720rpx;
  }
}

.v_list {
  padding: 0 30rpx 40rpx;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  
  .list_itme {
    width: 49%;
    margin-bottom: 20rpx;
    transition: all 0.3s ease;
    
    &.fade-in {
      animation: fadeIn 0.5s ease forwards;
    }
    .viose{
		width: 100%;
		height: 200rpx;
		video {
		  width: 100%;
		  height: 200rpx;
		  border-radius: 20rpx;
		  background-color: #000;
		}
	}

    .v_title {
      .name {
        font-weight: 400;
        font-size: 30rpx;
        width: 300rpx;
        color: #1D2129;
      }
    }

    .tps {
      font-size: 24rpx;
      color: #666666;
      width: 350rpx;
    }
  }
  
  // 骨架屏
  .skeleton-list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    
    .skeleton-item {
      width: 49%;
      margin-bottom: 20rpx;
      
      .skeleton-img {
        width: 100%;
        height: 200rpx;
        background: #F5F5F5;
        border-radius: 20rpx;
        margin-bottom: 10rpx;
        animation: skeleton-loading 1.5s infinite;
      }
      
      .skeleton-title {
        width: 90%;
        height: 30rpx;
        background: #F5F5F5;
        border-radius: 6rpx;
        margin-bottom: 8rpx;
        animation: skeleton-loading 1.5s infinite;
      }
      
      .skeleton-desc {
        width: 70%;
        height: 24rpx;
        background: #F5F5F5;
        border-radius: 6rpx;
        animation: skeleton-loading 1.5s infinite;
      }
    }
  }
  
  // 加载更多提示
  .loading-more {
    width: 100%;
    text-align: center;
    padding: 20rpx 0;
    color: #666;
    font-size: 26rpx;
    
    .loading-icon {
      display: flex;
      justify-content: center;
      margin-bottom: 10rpx;
      
      .dot {
        width: 10rpx;
        height: 10rpx;
        background-color: #23AC38;
        border-radius: 50%;
        margin: 0 5rpx;
        animation: loading 1s infinite ease-in-out;
        
        &:nth-child(2) {
          animation-delay: 0.2s;
        }
        
        &:nth-child(3) {
          animation-delay: 0.4s;
        }
      }
    }
  }
  
  // 没有更多数据
  .no-more-data {
    width: 100%;
    text-align: center;
    padding: 20rpx 0;
    color: #999;
    font-size: 26rpx;
  }
  
  // 空数据提示
  .empty-data {
    width: 100%;
    text-align: center;
    padding: 100rpx 0;
    
    // image {
    //   width: 200rpx;
    //   height: 200rpx;
    //   margin-bottom: 20rpx;
    // }
    
    text {
      font-size: 28rpx;
      color: #999999;
    }
  }
}

// 动画效果
@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: translateY(20rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes skeleton-loading {
  0% {
    background-color: rgba(165, 165, 165, 0.1);
  }
  50% {
    background-color: rgba(165, 165, 165, 0.3);
  }
  100% {
    background-color: rgba(165, 165, 165, 0.1);
  }
}

@keyframes loading {
  0%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  50% {
    transform: translateY(-10rpx);
    opacity: 1;
  }
}
</style>